package com.example.springdemo.Interceptors;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.springdemo.utils.JWTUtils;
import com.example.springdemo.utils.PassToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class AuthenticationInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Object handler) throws Exception {

            HandlerMethod handlerMethod=(HandlerMethod)handler;
            Method method=handlerMethod.getMethod();
            //检查是否有passtoken注释，有则跳过认证
            if (method.isAnnotationPresent(PassToken.class)) {
                return true;   //拦截器放行
            }

            Map<String, Object> map = new HashMap<>();
            map.put("code", 401);

            //获取请求头中的令牌
            String token = request.getHeader("Authorization");
    System.out.println(token);
            try {
                JWTUtils.verify(token.substring(token.lastIndexOf(" ")+1));
//              JWTUtils.verify(token);  //验证token
                return true;
            } catch (TokenExpiredException e) {
                e.printStackTrace();
                map.put("msg", "token过期");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("msg", "token⽆效");
            }

            //响应到前台: 将map转为json
            String json = new ObjectMapper().writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            return false;
        } }



